package com.hupu.jrs.widget.photodraweeview

import android.view.GestureDetector
import android.view.MotionEvent

class DefaultOnDoubleTapListener(attacher: Attacher) : GestureDetector.OnDoubleTapListener {

    private var mAttacher: Attacher? = null

    init {
        setPhotoDraweeViewAttacher(attacher)
    }

    override fun onSingleTapConfirmed(e: MotionEvent): Boolean {

        if (mAttacher == null) {
            return false
        }
        val draweeView = mAttacher!!.draweeView ?: return false

        if (mAttacher!!.onPhotoTapListener != null) {
            val displayRect = mAttacher!!.displayRect

            if (null != displayRect) {
                val x = e.x
                val y = e.y
                if (displayRect.contains(x, y)) {
                    val xResult = (x - displayRect.left) / displayRect.width()
                    val yResult = (y - displayRect.top) / displayRect.height()
                    mAttacher!!.onPhotoTapListener!!.onPhotoTap(draweeView, xResult, yResult)
                    return true
                }
            }
        }

        if (mAttacher!!.onViewTapListener != null) {
            mAttacher!!.onViewTapListener!!.onViewTap(draweeView, e.x, e.y)
            return true
        }

        return false
    }

    override fun onDoubleTap(event: MotionEvent): Boolean {
        if (mAttacher == null) {
            return false
        }

        try {
            val scale = mAttacher!!.scale
            val x = event.x
            val y = event.y

            if (scale < mAttacher!!.mediumScale) {
                mAttacher!!.setScale(mAttacher!!.mediumScale, x, y, true)
            } else if (scale >= mAttacher!!.mediumScale && scale < mAttacher!!.maximumScale) {
                mAttacher!!.setScale(mAttacher!!.maximumScale, x, y, true)
            } else {
                mAttacher!!.setScale(mAttacher!!.minimumScale, x, y, true)
            }
        } catch (e: Exception) {
            // Can sometimes happen when getX() and getY() is called
        }

        return true
    }

    override fun onDoubleTapEvent(event: MotionEvent): Boolean {
        return false
    }

    fun setPhotoDraweeViewAttacher(attacher: Attacher) {
        mAttacher = attacher
    }
}
